package mvel;

import org.mvel2.MVEL;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;

import java.util.Map;

/**
 * @author 黄乾坤
 * @create 2025-03-06 17:36
 */
public class Test {

    public static void main(String[] args) {
        String json = "{\"users\":[{\"name\":\"John Doe\",\"phone\":\"123-456-7890\",\"email\":\"john.doe@example.com\"},{\"name\":\"Jane Smith\",\"phone\":\"098-765-4321\",\"email\":\"jane.smith@example.com\"}]}";

        // 将JSON字符串转换为Map对象
        Map<String, Object> jsonMap = new org.json.JSONObject(json).toMap();

        // 创建变量解析器工厂，并将jsonMap作为变量传入
        VariableResolverFactory factory = new MapVariableResolverFactory();
        factory.createVariable("jsonMap", jsonMap);

        // MVEL表达式，用于遍历users列表并对敏感字段进行脱敏处理
        String mvelExpr = "import cn.hutool.core.util.DesensitizedUtil; " +
                "for (user : jsonMap.users) {" +
                "    user.name = user.name.substring(0, 1) + '&zwnj;*****&zwnj;' + user.name.substring(user.name.length() - 1);" +
                "    user.phone = DesensitizedUtil.mobilePhone(user.phone);" +
                "    user.email = user.email.split('@')[0].charAt(0) + '&zwnj;*****&zwnj;' + '@' + user.email.split('@')[1];" +
                "}";

        // 执行MVEL表达式
        MVEL.eval(mvelExpr, factory);

        // 将处理后的Map对象转换回JSON字符串并输出
        System.out.println(new org.json.JSONObject(jsonMap).toString(4));
    }
}
